package com.example.gyt.controller;



import com.example.gyt.pojo.UploadFile;
import com.example.gyt.util.DateUtil;
import com.example.gyt.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UploadController {

    //上传图片
    @RequestMapping("/uploadFile")
    @ResponseBody
    public ResultUtil uploadFile(@RequestParam("userId") String userId, @RequestParam("pictureUrl") MultipartFile file, HttpServletRequest request) {

        if(StringUtils.isEmpty(userId)){
            return ResultUtil.failure("用户ID不能为空");
        }

        //读取文件名字
        String fileName = file.getOriginalFilename();
        if(fileName.indexOf("\\") != -1){
            fileName = fileName.substring(fileName.lastIndexOf("\\"));
        }

        //将文件以时间格式命名
        fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpeg";

        //将图片存入到系统专属目录中
        String filePath = "src/main/webapp/extinct/files/images/" + userId + "/";
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //获取到图片的存储路径返回给用户，以便保存到数据库进行访问
        String urlPath = "/extinct/files/images/" + userId + "/" + fileName;

        UploadFile uploadFile = new UploadFile();
        uploadFile.setUserId(userId);
        uploadFile.setPictureTitle(fileName);
        uploadFile.setPictureUrl(urlPath);
        uploadFile.setCreateTime(DateUtil.getCurrentTime());

        //文件的保存
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath + fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
            return ResultUtil.success(uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failure("操作失败");
        }

    }


}
